package com.zxjbyte.yiyi.extension.job.core.listener;

import org.quartz.*;
import org.quartz.impl.matchers.EverythingMatcher;
import org.quartz.listeners.TriggerListenerSupport;

/**
 * 默认全局Trigger监听器
 *
 * @Author zhangxingjia
 * @Date 2023/11/2 20:10
 * @Version: 1.0
 */
public class DefaultGlobalTriggerListener extends TriggerListenerSupport {

    private final String name;

    public DefaultGlobalTriggerListener(String name){
        this.name = name;
    }

    public DefaultGlobalTriggerListener(){
        this("myDefaultGlobalTriggerListener");
    }


    public Matcher<TriggerKey> getMatcher() {
        return EverythingMatcher.allTriggers();
    }


    @Override
    public String getName() {
        return name;
    }

    /**
     * 在Trigger触发Job之前调用
     * @param trigger
     * @param context
     */
    @Override
    public void triggerFired(Trigger trigger, JobExecutionContext context) {
        getLog().info("Trigger fired >>> {} for job: {}", assembleTriggerInfo(trigger), assembleJobInfo(context));
    }

    /**
     * 在Trigger错过触发时调用。
     * @param trigger
     */
    @Override
    public void triggerMisfired(Trigger trigger) {
        getLog().info("Trigger misfired >>> {}", assembleTriggerInfo(trigger));
    }

    /**
     * 在Trigger触发Job之后调用。
     * @param trigger
     * @param context
     * @param triggerInstructionCode
     */
    @Override
    public void triggerComplete(Trigger trigger, JobExecutionContext context, Trigger.CompletedExecutionInstruction triggerInstructionCode) {
        getLog().info("Trigger complete >>> {} for Job: {} with instruction code: {}",
                assembleTriggerInfo(trigger), assembleJobInfo(context) ,triggerInstructionCode);
    }

    private String assembleTriggerInfo(Trigger trigger) {
        return "Trigger Name: " + trigger.getKey().getName() +
                ", Group: " + trigger.getKey().getGroup();
    }

    private String assembleJobInfo(JobExecutionContext context) {
        return "Job Name: " + context.getJobDetail().getKey().getName() +
                ", Group: " + context.getJobDetail().getKey().getGroup();
    }
}
